package com.term.appadmin.controller.company;

import com.term.appadmin.controller.BaseController;
import com.term.appadmin.pojo.query.company.CompanyListQuery;
import com.term.appadmin.pojo.query.company.CompanyQuery;
import com.term.appadmin.pojo.request.company.CompanyRequest;
import com.term.appadmin.pojo.view.company.CompanyElementView;
import com.term.appadmin.pojo.view.company.CompanyListView;
import com.term.appadmin.pojo.view.company.CompanyQueryElementView;
import com.term.dao.IBaseDao;
import com.term.domain.Company;
import com.term.domain.common.AndConditionSet;
import com.term.domain.common.Condition;
import com.term.domain.common.ConditionSet;
import com.term.domain.utils.DomainPage;
import com.term.service.ICompanyService;
import com.term.util.annotation.type.FuzzyQueryUtils;
import com.term.util.response.AjaxResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by chenGang on 2017/1/19.
 */
@Controller
public class CompanyController extends BaseController {

    @Resource
    private ICompanyService companyService;


    @RequestMapping(value = "/term/company/list")
    public String list(@Valid CompanyListQuery query, Model model) {
        this.setPageTitle(model,"公司列表");

        AndConditionSet andConditionSet = new AndConditionSet();
        andConditionSet.addCondition("name", query.getName(), Condition.MatchType.like);
        andConditionSet.addCondition("contacts", query.getContacts(), Condition.MatchType.like);

        DomainPage<Company> domainPage = companyService.getEntitiesByConditions(Company.class, andConditionSet, "id", IBaseDao.SortBy.DESC, query.getIndex(), query.getSize());
        model.addAttribute("page", new CompanyListView(domainPage, query));
        model.addAttribute("query", query);

        return "company/companylist";
    }



    @RequestMapping(value = "/term/company/add", method = RequestMethod.GET)
    public String add(Model model) {
        this.setPageTitle(model,"添加公司");
        this.enableGoBack(model);
        model.addAttribute("companyView",new CompanyElementView(new Company()));
        return "company/add";
    }



    @ResponseBody
    @RequestMapping(value = "/term/company/add", method = RequestMethod.POST)
    public AjaxResponse add(@Valid @RequestBody CompanyRequest request, BindingResult result) {
        if (result.hasErrors()) {
            return AjaxResponse.validationFail().msg("表单验证失败").reason(result.getAllErrors().get(0).getDefaultMessage());
        }
        Company company = initCompany(request);

        Optional<Company> companyOptional = companyService.add(company);

        if (!companyOptional.isPresent()) {
            return AjaxResponse.fail().msg("添加公司失败").reason("添加公司失败");
        }

        return AjaxResponse.ok().url("/term/company/list");
    }

    @RequestMapping(value = "/term/company/detail/{companyId:\\d+}", method = RequestMethod.GET)
    public String detail(Model model, @PathVariable Long companyId) {
        this.setPageTitle(model,"公司详情");
        this.enableGoBack(model);
        Optional<Company> company = companyService.getEntityById(Company.class, companyId);
        if (!company.isPresent()) {
            return "error";
        }
        model.addAttribute("companyView",new CompanyElementView(company.get()));
        return "company/add";
    }

    /**
     * 分页查询公司列表
     * @param query
     * @param bindingResult
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/term/company/query", method = RequestMethod.POST)
    public AjaxResponse query(@Valid @RequestBody CompanyQuery query, BindingResult bindingResult) {

        ConditionSet conditionSet = FuzzyQueryUtils.convertQueryToConditionSet(query);
        DomainPage<Company> domainPage = companyService.getEntitiesByConditions(Company.class, conditionSet, "id", IBaseDao.SortBy.DESC, query.getIndex(), query.getSize());
        if (domainPage == null || CollectionUtils.isEmpty(domainPage.getDomains())) {
            return AjaxResponse.noData();
        }

        List<CompanyQueryElementView> companyQueryElementViewList = domainPage.getDomains().stream().map(company -> new CompanyQueryElementView(company)).collect(Collectors.toList());

        return AjaxResponse.ok().data(companyQueryElementViewList);
    }


    /**
     * 初始化公司信息
     * @param request
     * @return
     */
    private Company initCompany(CompanyRequest request) {
        Company company = new Company();
        company.setId(request.getId());
        company.setName(request.getName());
        company.setAddress(request.getAddress());
        company.setContacts(request.getContacts());
        company.setMobile(request.getMobile());
        company.setFax(request.getFax());
        company.setEmail(request.getEmail());
        company.setLink(request.getLink());
        company.setRemark(request.getRemark());
        return company;
    }
}
